import { Application } from "egg";
import * as AutoIncrementFactory from "mongoose-sequence";
import { ObjectId } from "mongoose";
export interface DepartmentProps {
  id?: number; // 部门名称
  department_name: string; // 部门名称
  company_id: ObjectId; // 所属公司
  parent_id: ObjectId; // 父部门ID
  children: Array<DepartmentProps>; // 子部门ID
  is_delete: boolean; // 是否已删除
}
function initDepartmentModel(app: Application) {
  const mongoose = app.mongoose;
  const Schema = mongoose.Schema;
  const AutoIncrement = AutoIncrementFactory(mongoose);
  const DepartmentScheme = new Schema<DepartmentProps>(
    {
      department_name: { type: String, unique: true, required: true },
      company_id: { type: Schema.Types.ObjectId, ref: "Company" },
      parent_id: { type: Schema.Types.ObjectId, ref: "Department" },
      children: { type: Array },
      is_delete: { type: Boolean, default: false },
    },
    {
      timestamps: true,
      toJSON: {
        transform(_doc, ret) {
          delete ret.__v;
        },
      },
    }
  );
  DepartmentScheme.set("toJSON", { virtuals: true });
  DepartmentScheme.plugin(AutoIncrement, {
    inc_field: "id",
    id: "Department_counter",
  });
  return app.mongoose.model<DepartmentProps>("Department", DepartmentScheme);
}

export default initDepartmentModel;
